package cn.tangshh.universal.security.handler;

import cn.tangshh.universal.core.api.DR;
import cn.tangshh.universal.core.api.R;
import cn.tangshh.universal.core.api.RCode;
import cn.tangshh.universal.core.handler.GlobalExceptionHandler;
import cn.tangshh.universal.core.util.RequestUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 安全类异常处理
 *
 * @author Tang
 * @version v1.0
 * @since 2024/10/14
 */
@Slf4j
@Order(1)
@RestControllerAdvice
public class SecurityExceptionHandler extends GlobalExceptionHandler {
    /**
     * 未授权异常
     */
    @ExceptionHandler(InsufficientAuthenticationException.class)
    public R<?> insufficientAuthenticationException() {
        return DR.of(RCode.UNAUTHORIZED);
    }

    /**
     * 权限校验异常
     */
    @ExceptionHandler(AccessDeniedException.class)
    public R<?> accessDeniedException(HttpServletRequest request) {
        String uri = RequestUtil.getReqCurlUri(request);
        log.warn("[AccessDeniedException] uri:'{}' 权限校验失败", uri);
        return DR.of(RCode.NOT_PERMISSION);
    }
}